package com.gress.shop.shiro;

import com.gress.shop.util.HappyException;
import com.gress.shop.vo.SwalFactory;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.core.Ordered;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ExceptionInterceptor extends SimpleMappingExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		HandlerMethod method = (HandlerMethod)handler;
		ResponseBody sm = method.getMethodAnnotation(ResponseBody.class);

		if (ex instanceof HappyException || sm != null) {
			// ajax请求希望是弹框提示
			MappingJackson2JsonView jackson2JsonView = new MappingJackson2JsonView();
			jackson2JsonView.setExtractValueFromSingleKeyModel(true);
			ModelAndView modelAndView = new ModelAndView(jackson2JsonView);
			modelAndView.addObject("data",SwalFactory.getErrorSwal(ex.getMessage()));
			return modelAndView;
		}

		if (ex instanceof UnauthorizedException) {
			// 没有权限
			ModelAndView modelAndView = new ModelAndView();
			modelAndView.setViewName("permission/noAuto");
//			modelAndView.addObject("menu", sysPermissService.queryMenu());
			modelAndView.addObject("errorMessage", ex.getMessage());
			return modelAndView;
		}
		// 404 走web.xml
		// 其他请求异常
		ModelAndView mv = new ModelAndView();
		mv.setViewName("login/error");
		mv.addObject("exception", ex.toString().replaceAll("\n", "<br/>"));
		return mv;
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}
}
